package com.cl.code.generate.module.java.strategy;

import com.cl.code.common.utils.CamelCaseUtils;
import com.cl.code.generate.source.database.entity.TableMetadata;
import com.cl.code.generate.common.strategy.TableBaseGenerationStrategy;
import lombok.Getter;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * 实体生成策略实现类
 *
 * @author chengliang
 * @since 1.0.0
 */
public class JavaFileGenerationStrategy implements TableBaseGenerationStrategy {
    private final String tableName;
    private final String author;
    private final String version;
    private final Function<String, String> fileNameFunction;
    @Getter
    private final String packageName;
    @Getter
    private final String templatePath;
    @Getter
    private final String fileExtension = ".java";

    public JavaFileGenerationStrategy(String tableName, String templatePath, String packageName, String author, String version) {
        this(tableName, templatePath, packageName, (clasName) -> clasName, author, version);
    }

    /**
     * 实体生成策略构造函数
     *
     * @param tableName    数据库表名
     * @param templatePath 模板路径
     * @param packageName  Java包名
     * @param author       作者名称
     * @param version      版本号
     */
    public JavaFileGenerationStrategy(String tableName, String templatePath, String packageName, Function<String, String> fileNameFunction, String author, String version) {
        this.tableName = tableName;
        this.templatePath = templatePath;
        this.fileNameFunction = fileNameFunction;
        this.packageName = packageName;
        this.author = author;
        this.version = version;
    }

    /**
     * 获取输出路径
     *
     * @return 完整输出路径
     */
    @Override
    public String getOutputPath() {
        return packageName.replace(".", File.separator);
    }

    /**
     * 获取表名
     *
     * @return 数据库表名
     */
    @Override
    public String getTableName() {
        return tableName;
    }

    /**
     * 构建模板数据模型
     *
     * @param tableMetadata 表元数据
     * @return 模板数据模型
     */
    @Override
    public Map<String, Object> buildDataModel(TableMetadata tableMetadata) {
        // 创建基础数据模型
        Map<String, Object> dataModel = new HashMap<>();

        String className = CamelCaseUtils.toUpperCamelCase(tableMetadata.getTableName());
        String fileName = fileNameFunction.apply(className);
        // 设置包名和类名
        dataModel.put("packageName", packageName);
        dataModel.put("className", className);
        dataModel.put("fileName", fileName);
        dataModel.put("table", tableMetadata);
        dataModel.put("author", author);
        dataModel.put("version", version);
        // 构建字段模型
        dataModel.put("fields", tableMetadata.getFieldMetadataMap());

        return dataModel;
    }

}